import re

from rest_framework import serializers

from users.models import User


class UserSerializer(serializers.ModelSerializer):
    """用户管理序列化器"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email')

        extra_kwargs={
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
            },

            'username': {
                'max_length': 20,
                'min_length': 5,
            },

        }

# class UserCreateSerializer(serializers.ModelSerializer):
#
#     class Meta:
#
#         model = User
#         fields = ('id', 'username', 'mobile', 'email', 'password')
    def validate_mobile(self, value):

        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机格式不对')
        return value

    # 重写create方法
    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

